<?php

namespace App\Service\statistics;
use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\DataSpread;
use App\Model\Payment;
use App\Model\Playlet;
use App\Model\Company;
use App\Model\AppletCompany;
use App\Model\PlayletBind;
use App\Model\PlayletEpisodes;
use App\Model\RechargeGoods;
use App\Model\RechargeTemplate;
use App\Model\SystemOrderDay;
use App\Model\SystemOrderDayCount;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;

class StatisticsService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
        $this->userAppletIds = $this->getUserAppletInfo();
    }

    const STATUS_ENABLE  = 1;

    public function orderSearch(Array $params,$export=0){

        $pageSize       = $params['pageSize'] ?? 10;
        $page           = $params['page'] ?? 1;
        $playlet_id     = $params['playlet_id'] ?? '';
        $date     = $params['date'] ?? '';
        $today_time = date('Y-m-d',time());
        $userInfo = $this->getUserAppletInfo(2);
        //管理员能看到所有
        if($userInfo['role']['is_admin'] != 1){
            //获取这个用户的company 查找对应的小城，找到对应的短剧

            $applet_ids = AppletCompany::query()->where(['company_id' => $userInfo['company_id']])->pluck('applet_id');
            if(empty($applet_ids)){
                return [];
            }
            $playlet_ids = AppletPlayletRel::query()->whereIn('applet_id',$applet_ids)->pluck('playlet_id');
            if(empty($playlet_ids)){
                return [];
            }
        }


        $commonArr = [Db::raw('SUM(order_pay_count) as order_pay_count'),
            Db::raw('SUM(order_wx_pay_count) as order_wx_pay_count'),
            Db::raw('SUM(order_virtually_pay_count) as order_virtually_pay_count'),
            Db::raw('SUM(order_wx_pay_amonut) as order_wx_pay_amonut'),
            Db::raw('SUM(order_virtually_pay_amount) as order_virtually_pay_amount'),
            Db::raw('SUM(dy_pay_count) as dy_pay_count'),
            Db::raw('SUM(dy_pay_amount) as dy_pay_amount')
            ];

        $selectArr = array_merge(['date',
            Db::raw('playlet.main_playlet_id as playlet_id'),
            Db::raw('0 as order_amount')
        ],$commonArr);

        $unionArr = array_merge(['date',
            Db::raw('playlet.main_playlet_id as playlet_id'),
            Db::raw('SUM(order_amount) as order_amount')
        ],$commonArr);

        //获取所拥有的
        $query = SystemOrderDay::query()->select($selectArr);
        $unionQuery = Db::table('system_order_day_count')->select($unionArr);

        if(!empty($playlet_ids)){
            $query->whereIn('playlet.main_playlet_id',$playlet_ids);
            $unionQuery->whereIn('playlet.main_playlet_id',$playlet_ids);
        }
        if(!empty($playlet_id) && $playlet_id != 1){
            $query->where('playlet.main_playlet_id',$playlet_id);
            $unionQuery->where('playlet.main_playlet_id',$playlet_id);
        }
        if(!empty($date)){

            $date[0] = date('Y-m-d',$date[0]/1000);
            $date[1] = date('Y-m-d',$date[1]/1000);

            if( $date[0] <$today_time && $today_time < $date[1]){
                $query->where('date',$today_time);
            }else{
                $query->where('date',null);
            }
            $unionQuery->whereBetween('date',$date);
        }else{
            $query->where('date',$today_time);
        }
        $query->leftJoin('playlet','playlet.id','=','system_order_day.playlet_id');
        $unionQuery->leftJoin('playlet','playlet.id','=','system_order_day_count.playlet_id');
        $query->where('playlet_id','!=',0);
        $unionQuery->where('playlet_id','!=',0);

        $query->groupBy(['date','playlet.main_playlet_id']);
        $unionQuery->groupBy(['date','playlet.main_playlet_id']);
        $query->union($unionQuery);

        $countQuery = $query;
        $countResult = $countQuery->get();
        $models = $query->orderBy('date','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];

        //获取所有短剧的配置
        $bindData = PlayletBind::query()->select(['playlet_id','amount','type'])->get();

        if(!empty($bindData)){
            $bindKeyVal =array();
            $bindKeyType = array();
            foreach ($bindData as $bindDatum){
                $bindKeyVal[$bindDatum->playlet_id] = $bindDatum->amount;
                $bindKeyType[$bindDatum->playlet_id] = $bindDatum->type;
            }
        }
        $countData = [];
        $countInsertData['order_pay_count'] = 0;
        $countInsertData['order_wx_pay_count'] = 0;
        $countInsertData['order_virtually_pay_count'] = 0;
        $countInsertData['order_wx_pay_amonut'] = 0;
        $countInsertData['order_virtually_pay_amount'] = 0;
        $countInsertData['order_amount'] = 0;
        foreach ($countResult as $item){
            $data = $item->toArray();
            if($item->date == $today_time) {
                if (!empty($bindKeyVal[$item->playlet_id])) {
                    $amount = $bindKeyVal[$item->playlet_id] / 100;
                } else {

                    $amount = 1;
                }
                $order_wx_pay_amonut = ceil($data['order_wx_pay_amonut']/100*$amount);
                $order_virtually_pay_amount = ceil($data['order_virtually_pay_amount']/100*$amount);
                if(!empty($bindKeyType[$item->playlet_id]) && $bindKeyType[$item->playlet_id] == 2){
                    $dy_pay_amount = ceil($data['dy_pay_amount']/100*$amount);
                }else {
                    $dy_pay_amount = 0;
                    $data['dy_pay_count'] = 0;
                }

                $data['order_pay_count'] = ceil($data['order_pay_count']*$amount);
                $data['order_wx_pay_count'] = ceil($data['order_wx_pay_count']*$amount);
                $data['order_virtually_pay_count'] = ceil(($data['order_virtually_pay_count']+$data['dy_pay_count'])*$amount);
                $data['order_wx_pay_amonut']  = sprintf("%.2f",$order_wx_pay_amonut);
                $data['order_virtually_pay_amount']  =sprintf("%.2f",$order_virtually_pay_amount+$dy_pay_amount);
                $data['order_amount']  = sprintf("%.2f",floatval($data['order_wx_pay_amonut']+$data['order_virtually_pay_amount']));
            }else{
                $data['order_virtually_pay_count'] = $data['order_virtually_pay_count']+$data['dy_pay_count'];
                $data['order_virtually_pay_amount']  =$data['order_virtually_pay_amount']+$data['dy_pay_amount'];
            }
            $countInsertData['date'] = '汇总';
            $countInsertData['playlet_name'] = '汇总';
            $countInsertData['order_pay_count']  = $data['order_pay_count'] + $countInsertData['order_pay_count'];
            $countInsertData['order_wx_pay_count']  = $data['order_wx_pay_count'] + $countInsertData['order_wx_pay_count'];
            $countInsertData['order_virtually_pay_count']  =$data['order_virtually_pay_count'] + $countInsertData['order_virtually_pay_count'];
            $countInsertData['order_wx_pay_amonut']  = sprintf("%.2f",$data['order_wx_pay_amonut'] + $countInsertData['order_wx_pay_amonut']);
            $countInsertData['order_virtually_pay_amount']  = sprintf("%.2f",$data['order_virtually_pay_amount'] + $countInsertData['order_virtually_pay_amount']);
            $countInsertData['order_amount']  = sprintf("%.2f",$data['order_amount'] + $countInsertData['order_amount']);
        }


        foreach ($items as $item){
            $data = $item->toArray();

            if(!empty($item->playlet)){
                $data['playlet_name'] = $item->playlet->name;
            }else{
                $data['playlet_name'] = '';
            }

            if($item->date == $today_time){

                if(!empty($bindKeyVal[$item->playlet_id])){
                    $amount = $bindKeyVal[$item->playlet_id]/100;
                }else {

                    $amount = 1;
                }
                $order_wx_pay_amonut = ceil($data['order_wx_pay_amonut']/100*$amount);
                $order_virtually_pay_amount = ceil($data['order_virtually_pay_amount']/100*$amount);
                if(!empty($bindKeyType[$item->playlet_id]) && $bindKeyType[$item->playlet_id] == 2){
                    $dy_pay_amount = ceil($data['dy_pay_amount']/100*$amount);
                }else {
                    $dy_pay_amount = 0;
                    $data['dy_pay_count'] = 0;
                }

                $data['order_pay_count']= ceil($data['order_pay_count']*$amount);
                $data['order_wx_pay_count'] = ceil($data['order_wx_pay_count']*$amount);
                $data['order_virtually_pay_count'] = ceil(($data['order_virtually_pay_count']+$data['dy_pay_count'])*$amount);
                $data['order_wx_pay_amonut']  = sprintf("%.2f",$order_wx_pay_amonut);
                $data['order_virtually_pay_amount']  =sprintf("%.2f",$order_virtually_pay_amount+$dy_pay_amount);
                $data['order_amount']  = sprintf("%.2f",floatval($data['order_wx_pay_amonut']+$data['order_virtually_pay_amount']));

            }else{
                $data['order_virtually_pay_count']  = $data['order_virtually_pay_count']+$data['dy_pay_count'];
                $data['order_wx_pay_amonut']  = sprintf("%.2f",floatval($data['order_wx_pay_amonut']));
                $data['order_virtually_pay_amount']  =sprintf("%.2f",floatval($data['order_virtually_pay_amount']+$data['dy_pay_amount']));
                $data['order_amount']  = sprintf("%.2f",floatval($data['order_amount']));
            }
            $selectData[] =$data;
        }
        $countInfo[0] = $countInsertData;
        $data = $models->toArray();
        $data['data'] =  array_merge($countInfo,$selectData);
        return $data;
    }


    public function getplayletInfo(Array $params){

        $applet_ids     = $params['applet_ids'] ?? '';

        $date     = $params['date'] ?? '';
        if(empty($applet_ids)){
            return [];
        }
        $userInfo = $this->getUserAppletInfo(2);
        //管理员能看到所有
        if($userInfo['role']['is_admin'] != 1){
            //获取这个用户的company 查找对应的小城，找到对应的短剧
            if($applet_ids == 1){
                $applet_ids = AppletCompany::query()->where(['company_id' => $userInfo['company_id']])->pluck('applet_id');
                if(empty($applet_ids)){
                    return [];
                }
                $playlet_ids = AppletPlayletRel::query()->whereIn('applet_id',$applet_ids)->pluck('playlet_id');
                if(empty($playlet_ids)){
                    return [];
                }

            }else{

                $playlet_ids = AppletPlayletRel::query()->whereIn('applet_id',[$applet_ids])->pluck('playlet_id');
                if(empty($playlet_ids)){
                    return [];
                }
            }

            $playletInfo =  Playlet::query()->whereIn('id',$playlet_ids)->select(['id as value','name as label'])->get();
            if(!empty($playletInfo)){
                $returnData[] = ['value' => 1,'label' => '全部短剧'];
                $playletInfo = array_merge($returnData,$playletInfo->toArray());
                return $playletInfo;
            }
        }else{
            $playletInfo =  Playlet::query()->select(['id as value','name as label'])->get();
            if(!empty($playletInfo)){
                $returnData[] = ['value' => 1,'label' => '全部短剧'];
                $playletInfo = array_merge($returnData,$playletInfo->toArray());
                return $playletInfo;
            }
        }
    }

}